package com.example.springbootdemo.micrometer;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.composite.CompositeMeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author chenxiaomeng
 */
@RestController
@RequestMapping("api")
public class Demo1 {
    private static final String METRIC_CATEGORY = "api_id";

    private final MeterRegistry meterRegistry;
    public Demo1(MeterRegistry  meterRegistry) {
        this.meterRegistry = meterRegistry;
    }

    /**
     * 请求API计数
     * @param apiId
     */
    @RequestMapping("count/{apiId}")
    public void count(@PathVariable("apiId") Integer apiId){
        final Counter counter = createCounter("ares_api_query_count", "API请求数量",
                METRIC_CATEGORY, String.valueOf(apiId));
        counter.increment();
        System.out.println(counter.count());
    }


    @RequestMapping("count1/{apiId}")
    public void count1(@PathVariable("apiId") Integer apiId){


    }


    private Counter createCounter(String counterName, String desc, String... tags) {
        return Counter.builder(counterName)
                .description(desc)
                .tags(tags)
                .register(meterRegistry);
    }


    public static void main(String[] args) {

        CompositeMeterRegistry composite = new CompositeMeterRegistry();
        SimpleMeterRegistry simple = new SimpleMeterRegistry();
        composite.add(simple);

        Counter compositeCounter = composite.counter("counter");

        for (int i = 0; i < 50; i++) {
            new Thread(()->
            {
                for (int j = 0; j < 100; j++) {
                    compositeCounter.increment();
                }
            }).start();
        }
//
//        for (int i = 0; i < 100; i++) {
//            compositeCounter.increment();
//        }

        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(compositeCounter.count());
//        Counter counter = simple.counter("counter");
//        System.out.println(counter.count());


    }

    private static void moreThread(){
        CompositeMeterRegistry composite = new CompositeMeterRegistry();
        Counter counter = composite.counter("counter");
        for (int i = 0; i < 5; i++) {
            new Thread(()->
            {
                for (int j = 0; j < 100; j++) {
                    counter.increment();
                }
            }).start();
        }
        System.out.println(counter.count());
    }




}
